package com.yp.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yp.common.ErrorCode;
import com.yp.exception.BusinessException;
import com.yp.model.domain.User;
import com.yp.service.UserService;
import com.yp.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.yp.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author 12691
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2025-09-01 10:24:44
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    private UserMapper userMapper;

    private static final  String SALT = "yupi";



    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword,String pantCode) {
//        1.校验
        if (StringUtils.isAllBlank(userAccount,userPassword,checkPassword ,pantCode)){

//            return -1;
            throw new BusinessException(ErrorCode.PARAM_ERROR,"数据为空");
        }

        if (userAccount.length() < 4) {
//            return -1;
            throw new BusinessException(ErrorCode.PARAM_ERROR,"用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8){
//            return -1;
            throw new BusinessException(ErrorCode.PARAM_ERROR,"密码过短");
        }

        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return -1;
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            return -1;
        }

        if (pantCode.length() > 5 ){
//            return  -1;
            throw new BusinessException(ErrorCode.PARAM_ERROR,"星球编号太长");
        }

        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {

//            return -1;
            throw new BusinessException(ErrorCode.PARAM_ERROR,"账户重复");
        }

        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pantCode", pantCode);
        count = userMapper.selectCount(queryWrapper);
        if (count > 0) {

//            return -1;
            throw new BusinessException(ErrorCode.PARAM_ERROR,"星球编号重复");
        }

        // 2.加密

        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 3.插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPantCode(pantCode);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            return -1;
        }
        return user.getId();

    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {

        //1.校验
        if (StringUtils.isAllBlank(userAccount,userPassword)){
//            return null;
            throw new BusinessException(ErrorCode.PARAM_ERROR,"数据为空");
        }

        if (userAccount.length() < 4) {
            return null;
        }
        if (userPassword.length() < 8 ){
            return null;
        }

        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }

        // 2.加密

        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());


        // 账户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);

        User user = userMapper.selectOne(queryWrapper);

        if (user == null){
            log.info("user login failed");
            return null;
        }

        User safetUser =  getSafetyUser(user);




        request.getSession().setAttribute(USER_LOGIN_STATE,safetUser);




        return safetUser;
    }

    @Override
    public User getSafetyUser(User orgUser){
        if (orgUser ==null){
            return null;
        }
        User safetUser =  new User();
        safetUser.setId(orgUser.getId());
        safetUser.setUsername(orgUser.getUsername());
        safetUser.setUserAccount(orgUser.getUserAccount());
        safetUser.setAvatarUrl(orgUser.getAvatarUrl());
        safetUser.setGender(orgUser.getGender());
        safetUser.setEmail(orgUser.getEmail());
        safetUser.setUserStatus(orgUser.getUserStatus());
        safetUser.setPhone(orgUser.getPhone());
        safetUser.setCreateTime(orgUser.getCreateTime());
        safetUser.setUserRole(orgUser.getUserRole());
        safetUser.setPantCode(orgUser.getPantCode());
        safetUser.setTags(orgUser.getTags());
        return safetUser;
    }

    @Override
    public int userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    /**
     *   根据标签搜索用户。
     * @param tagNameList  用户要搜索的标签
     * @return
     */
    @Override
    public List<User> searchUsersByTags(List<String> tagNameList){
        if (CollectionUtils.isEmpty(tagNameList)){
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        //拼接tag
//        // like '%Java%' and like '%Python%'
//        for (String tagList : tagNameList) {
//            queryWrapper = queryWrapper.like("tags", tagList);
//        }
//        List<User> userList = userMapper.selectList(queryWrapper);
//        return  userList.stream().map(this::getSafetyUser).collect(Collectors.toList());

        QueryWrapper queryWrapper = new QueryWrapper<>();
        List<User> userList = userMapper.selectList(queryWrapper);
        Gson gson = new Gson();
        //2.判断内存中是否包含要求的标签
        return userList.stream().filter(user -> {
            String tagstr = user.getTags();
            if (StringUtils.isBlank(tagstr)){
                return false;
            }
            Set<String> tempTagNameSet =  gson.fromJson(tagstr,new TypeToken<Set<String>>(){}.getType());
            for (String tagName : tagNameList){
                if (!tempTagNameSet.contains(tagName)){
                    return false;
                }
            }
            return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());
    }
}




